#! /usr/bin/env python

import sys, threading, socket, re
all_clients = []
class ClientWriter(threading.Thread):
	def __init__(self, client_sock, number, buffer):
		self.client_sock = client_sock
		self.number = number
		threading.Thread.__init__ ( self )
		self.buffer = buffer #in byte form
	def run(self):
		sock_pos = all_clients.index(self.client_sock)
		for sock in all_clients:
			if(sock_pos != all_clients.index(sock)):
				sock.send(b'Player '+self.number.encode()+b': '+self.buffer)
			
class ClientHandler(threading.Thread):
	def __init__(self, client_sock):
		self.client_sock = client_sock
		self.number = str(len(all_clients)+1)
		threading.Thread.__init__ ( self )
	def run(self):
		try:
			all_clients.append(client_sock)
			self.client_sock.send(b'You are player '+bytes(self.number,'utf-8')+b'. There are '+str(len(all_clients)).encode()+b' players in the chat.')
			while 1:
				self.chunk = self.client_sock.recv(1024)
				if(self.chunk==b'quit'):
					break
				if(len(self.chunk)>0):
					writer = ClientWriter(self.client_sock,self.number,self.chunk).start()
			self.client_sock.send(b'quit')
			all_clients.remove(self.client_sock)
			self.client_sock.close()
		except:
			all_clients.remove(self.client_sock)
			self.client_sock.close()

if(len(sys.argv)!=2): 
	port = 15000
	# print('Usage socket_chat_server [port]')
	# quit()
# Set up our socket.
else:
	port = int(sys.argv[1])
chatsvr_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
chatsvr_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  
chatsvr_sock.bind(('10.238.242.244',port))
chatsvr_sock.listen(5)
print("Chat server is up and running...")
while 1:	
	# Proxy server gets request
	(client_sock,address)=chatsvr_sock.accept()
	# New thread deals with request
	ClientHandler(client_sock).start()
chatsvr_sock.close()